#pragma once

#include "TcpSocket.hpp"
#include <memory>
#include <pthread.h>
#include <functional>
#include <vector>

using func_t = std::function<void(int, const Ser_Change::DataConversion&)>;

class Server;

class ThreadData
    {
    public:
        ThreadData(int socket, Server *_ser, Ser_Change::DataConversion* sch)
            : _socket(socket), _ser_host(_ser)
            , _sch(sch)
        {}
        
        Ser_Change::DataConversion* _sch;  // 堆上
        int _socket;
        Server *_ser_host; // 提供服务对象
    };

class Server
{
    static void* routine(void* args)
    {
        pthread_detach(pthread_self());
        ThreadData* tmp = static_cast<ThreadData*>(args);
        tmp->_ser_host->service_run(tmp->_socket, *tmp->_sch);

        delete tmp->_sch;
        delete tmp;
        return nullptr;
    }


public:
    Server(uint16_t port) // 这个初始化可能有问题
    {
        lisen_sock = _ms._socket_set();
        _ms.bind_set(lisen_sock, port);
        _ms.listen_run(lisen_sock);
    }

    void Stat()
    {
        for (;;)
        {
            struct sockaddr_in send_; // 请求方信息
            uint16_t send_port;
            int actual_socket = -1;
            actual_socket = _ms.accept_run(lisen_sock, &send_, &send_port);
            if (actual_socket < 0)
            {
                continue;
            }
            // 进行反序列化
            // 提取数据，然后填入
            char buff[1024];
            bzero(buff, sizeof buff);
            _ms.Recv(actual_socket, buff, (sizeof buff) -1);
            std::string recv(buff);
            // std::cout << recv << std::endl;
            while (!recv.empty())
            {
                Ser_Change::DataConversion* tmp = new Ser_Change::DataConversion;
                tmp->Disserialize(recv); //获取一份形成一个数据包

                ThreadData* it= new ThreadData(actual_socket, this, tmp);
                pthread_t  pt;
                pthread_create(&pt, nullptr, routine, (void*)it);
            }
        }

    }

    void Bind_func(func_t func)
    {
        _funcs.push_back(func);
    }

private:
    // 对任务逐一调用
    void service_run(int socket, const Ser_Change::DataConversion& ser)
    {
        for (auto& it : _funcs)
        {
            it(socket, ser);
        }
    }

    struct sockaddr_in _host; 
    int lisen_sock = -1;
    MySocket _ms;
    std::vector<func_t> _funcs;
};



